package com.goldplusgold.tradedelay.app.market.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.TextView;

import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.market.MarketManager;
import com.goldplusgold.tradedelay.app.market.eventbus.FiveRangeMessageEvent;
import com.goldplusgold.tradedelay.app.market.pojo.CMinute;
import com.goldplusgold.tradedelay.app.market.pojo.FenshiDataResponse;
import com.goldplusgold.tradedelay.app.market.pojo.FenshiParam;
import com.goldplusgold.tradedelay.app.market.widget.chartview.CrossView;
import com.goldplusgold.tradedelay.app.market.widget.chartview.FenshiView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2016/10/25.
 */
public class FenshiFragment extends LineBaseFragment implements FenshiView.OnCrossListener, MarketManager.MinuteReceiver {
    @BindView(R.id.sold_five)
    TextView soldFive;
    @BindView(R.id.sold_five_volume)
    TextView soldFiveVolume;
    @BindView(R.id.sold_four)
    TextView soldFour;
    @BindView(R.id.sold_four_volume)
    TextView soldFourVolume;
    @BindView(R.id.sold_three)
    TextView soldThree;
    @BindView(R.id.sold_three_volume)
    TextView soldThreeVolume;
    @BindView(R.id.sold_two)
    TextView soldTwo;
    @BindView(R.id.sold_two_volume)
    TextView soldTwoVolume;
    @BindView(R.id.sold_one)
    TextView soldOne;
    @BindView(R.id.sold_one_volume)
    TextView soldOneVolume;
    @BindView(R.id.buy_one)
    TextView buyOne;
    @BindView(R.id.buy_one_volume)
    TextView buyOneVolume;
    @BindView(R.id.buy_two)
    TextView buyTwo;
    @BindView(R.id.buy_two_volume)
    TextView buyTwoVolume;
    @BindView(R.id.buy_three)
    TextView buyThree;
    @BindView(R.id.buy_three_volume)
    TextView buyThreeVolume;
    @BindView(R.id.buy_four)
    TextView buyFour;
    @BindView(R.id.buy_four_volume)
    TextView buyFourVolume;
    @BindView(R.id.buy_five)
    TextView buyFive;
    @BindView(R.id.buy_five_volume)
    TextView buyFiveVolume;
    @BindView(R.id.cff_fenshiview)
    FenshiView fenshiView;
    @BindView(R.id.cff_cross)
    CrossView crossView;
    //滑动十字线时，显示对应点详情的地方
    @BindView(R.id.cff_msg)
    TextView msgText;
    private long volumeTotal = 0;
    private double amountTotal = 0;
    private LinkedHashMap<Long, CMinute> mTimeSharingList = new LinkedHashMap<>();

    private List<CMinute> dataList = new ArrayList<>();

    private String lastSettle;

    volatile boolean isChange = false;
    //分时数据
    private FenshiDataResponse minuteData = new FenshiDataResponse();
    private Market.InstType mInstType;
    /**
     * 循环刷新界面
     */
    private final   MyHandler refreshHandler = new MyHandler(this) ;

    public static FenshiFragment newInstance(Market.InstType instType) {
        Bundle args = new Bundle();
        args.putSerializable("instType", instType);
        FenshiFragment fragment = new FenshiFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mInstType = (Market.InstType) args.getSerializable("instType");
        }
        MarketManager.getInstance().setMinuteReceiver(this);
    }

    @Override
    public void onResume() {
        super.onResume();
//        EventBus.getDefault().register(this);
//        MarketManager.getInstance().sendRequestMsg(mInstType);
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
//        MarketManager.getInstance().setMinuteReceiver(null);
    }

    public void changeType(Market.InstType instType){
        if(this.mInstType == instType){
            return;
        }
        this.mInstType = instType;
        isChange = true;
        dataList.clear();
        if (fenshiView != null)
            fenshiView.postInvalidate();
        MarketManager.getInstance().sendRequestMsg(this.mInstType);
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_minute;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fenshiView.setOnDoubleTapListener(this);
        fenshiView.setOnCrossListener(this);
        fenshiView.setUsedViews(crossView, msgText);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && mInstType != null) {
//            MarketManager.getInstance().sendRequestMsg(mInstType);
            Log.e("xsy", "setUserVisibleHint sendRequestMsg  mInstType" + mInstType);
        }

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case INDEX_VOL:
//                fenshiView.showVOL();
                break;
            case INDEX_ZJ:
                //TODO 显示指标资金
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDismiss() {
        Fragment f = getParentFragment();
        if (f != null && f instanceof QuotationChartFragment) {
            ((QuotationChartFragment) f).hideMinuteTitle();
        }
    }

    @Override
    public void onShow(CMinute cMinute, double lastSettle) {
        Fragment f = getParentFragment();
        if (f != null && f instanceof QuotationChartFragment) {
            ((QuotationChartFragment) f).showMinuteTitle(cMinute, lastSettle);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFiveRangeEventBus(FiveRangeMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEFIVERANGE && event.getIdentification().getInstType() == mInstType) {
            fillFiveRangeData(event.getQuoteFiveRange());
        }
    }


    public void setItemValueAndColor(TextView item, String buyPrice, double lastSettle) {
        item.setText(buyPrice);
        double price = StringConvertNumber.parseDouble(buyPrice);
        if (lastSettle > price) {
            item.setTextColor(getResources().getColor(R.color.color_green));
        } else if (lastSettle == price) {
            item.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        } else {
            item.setTextColor(getResources().getColor(R.color.color_red_two));
        }
    }

    private void fillFiveRangeData(Market.QuoteFiveRange quoteFiveRange) {
        double lastSettle = StringConvertNumber.parseDouble(quoteFiveRange.getLastSettle());
        setItemValueAndColor(buyFive, quoteFiveRange.getBuyPrice5(), lastSettle);
        setItemValueAndColor(buyFour, quoteFiveRange.getBuyPrice4(), lastSettle);
        setItemValueAndColor(buyThree, quoteFiveRange.getBuyPrice3(), lastSettle);
        setItemValueAndColor(buyTwo, quoteFiveRange.getBuyPrice2(), lastSettle);
        setItemValueAndColor(buyOne, quoteFiveRange.getBuyPrice1(), lastSettle);

        buyFiveVolume.setText(quoteFiveRange.getBuyVolume5() + "");
        buyFourVolume.setText(quoteFiveRange.getBuyVolume4() + "");
        buyThreeVolume.setText(quoteFiveRange.getBuyVolume3() + "");
        buyTwoVolume.setText(quoteFiveRange.getBuyVolume2() + "");
        buyOneVolume.setText(quoteFiveRange.getBuyVolume1() + "");

        setItemValueAndColor(soldFive, quoteFiveRange.getSellPrice5(), lastSettle);
        setItemValueAndColor(soldFour, quoteFiveRange.getSellPrice4(), lastSettle);
        setItemValueAndColor(soldThree, quoteFiveRange.getSellPrice3(), lastSettle);
        setItemValueAndColor(soldTwo, quoteFiveRange.getSellPrice2(), lastSettle);
        setItemValueAndColor(soldOne, quoteFiveRange.getSellPrice1(), lastSettle);

        soldFiveVolume.setText(quoteFiveRange.getSellPolume5() + "");
        soldFourVolume.setText(quoteFiveRange.getSellPolume4() + "");
        soldThreeVolume.setText(quoteFiveRange.getSellPolume3() + "");
        soldTwoVolume.setText(quoteFiveRange.getSellPolume2() + "");
        soldOneVolume.setText(quoteFiveRange.getSellPolume1() + "");
    }


    private void sendTimeSharingMessage() {
        Message msg = refreshHandler.obtainMessage();
        msg.what = 1;
        refreshHandler.sendMessage(msg);
    }

    public void refreshView(){
        if (!isAvailableActivity() || fenshiView == null) {
            return;
        }
        if(dataList.size() == 0)
            return;
        double lastSettleValue = StringConvertNumber.parseDouble(lastSettle);
        FenshiParam fenshiParam = new FenshiParam();
        fenshiParam.setDuration("9:30-11:30|13:00-15:00");
        minuteData.setParam(fenshiParam);
        minuteData.getParam().setLast(lastSettleValue);
        if (dataList.size() >= 1) {
            minuteData.getParam().setUntil(dataList.get(dataList.size() - 1).getTime());
        }
        minuteData.setData(new ArrayList<CMinute>(dataList));
        fenshiView.setDataAndInvalidate(minuteData, mInstType);
    }

    @Override
    public void onReceive(List<CMinute> list, String lastSettle) {
        this.lastSettle = lastSettle;
        this.dataList = list;
        sendTimeSharingMessage();
    }

    private static class MyHandler extends Handler {
        private final WeakReference<FenshiFragment> mFragment;

        public MyHandler(FenshiFragment fragment) {
            mFragment = new WeakReference<FenshiFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mFragment.get() == null) {
                        return;
                    }
                    mFragment.get().refreshView();
                    break;
                default:
                    break;
            }
        }
    }
}
